<?php
declare (strict_types = 1);
namespace app\common\model\content;

use think\Exception;
use think\facade\Db;
use think\facade\Log;

class ArticleForm
{
    const BRIEF_LEN = 70;

    //文章模型
    private $model;
    //场景
    public $scene = 'normal';


    //保存文章
    public function store(array $data){

        // 启动事务
        Db::startTrans();
        try {
            //保存文章信息
            $this->saveArticle($data);

            //保存文章内容
            //$this->saveContent($data);

            //保存关联标签
            $this->saveTags($data);

            //创建文章封面
            $this->setCover();

            // 提交事务
            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
            Log::error($e->getMessage());
            Db::rollback();
            throw $e;
        }
        return true;
    }
    //**保存文章
    private function saveArticle(array $data){
        $model = $this->getModel();
        if( $model->isExists() ){
            $cModel = Content::where('article_id','=', $this->getModel()->id)->find();
        }else{
            $cModel = new Content();
        }
        //保存文章信息
        if( !$model->save($data) || !$cModel->save(['article_id'=>$model->id,'content'=>$data['content']]))
            throw new Exception('保存文章失败.');
    }

    //**保存标签 保存关联信息
    private function saveTags(array $data){

        //清空标签
        if (!Tag::cleanTags((int)$this->getModel()->id))
            throw new Exception('置空标签失败.');

        //保存标签
        if (!empty($data['tags'])){

            try{
                Tag::store($data['tags'], (int)$this->model->id);
            }catch (\Exception $e){
                throw new Exception('保存标签错误.');
            }

        }


    }

    //**设置文章封面
    private function setCover(){
        //如果有设置封面就退出
        $model = $this->getModel();
        if ($model->image && strpos($model->image, '/') !== 0) return true;

        //没有手动设置 那就自动生成根据内容里的图片
        $model->image = (string) Image::where(['article_id'=>$model->id])->order(['create_time'=>'ASC','id'=>'ASC'])->value('image');
        return $model->save();
    }

    //获取当前文章模型
    public function getModel(){
        if($this->model instanceof Article) return $this->model;
        $this->model = new Article();
        return $this->model;
    }
    //设置当前文章模型
    public function setModel(Article $model){
        $this->model = $model;
    }

    public function __call($name, $arguments)
    {
        if(method_exists($this, $name)){
            return $this->$name($arguments);
        }
        return $this->getModel()->$name($arguments);
    }

    public function __get($name)
    {
        if(property_exists($this, $name)){
            return $this->$name;
        }
        return $this->getModel()->$name;
    }


}